package com.promise.jokerdream.work.penguin

import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.repository.foldWithApiException
import com.promise.jokerdream.utils.AppContext
import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult
import java.util.Calendar

// 六门会武工作
class SectMeleeWork(override val uin: String): BaseWork(uin) {

    override val name: String
        get() = "六门会武"

    private val gameApi = GameApi.Companion.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.Companion.getInstance(AppContext.get()) }

    override suspend fun executeWork(): WorkResult {
        return try {
            // 1. 查询助威然后助威
            processCheer()

            // 2. 查询领奖，然后领奖
            processReward()

            WorkResult.Success
        } catch (e: Exception) {
            historyManager.addHistory(name, e.message)
            WorkResult.Failure(e, e.message)
        }
    }

    private suspend fun processCheer(): WorkResult {
        // 查询六门会武助威信息
        val queryResult = gameApi.querySectMeleeCheer()
        return queryResult.foldWithApiException(
            onSuccess = { response ->
                // 检查是否已助威
                if (response.cheerSect == 0) {
                    // 未助威，执行助威
                    val cheerResult = gameApi.cheerSectMelee()
                    cheerResult.foldWithApiException(
                        onSuccess = { cheerResponse ->
                            historyManager.addHistory(name, cheerResponse.getDescription())
                            WorkResult.Success
                        },
                        onFailure = { code, msg ->
                            historyManager.addHistory(name, msg)
                            WorkResult.Failure(Exception(msg), msg)
                        }
                    )
                } else {
                    WorkResult.Success
                }
            },
            onFailure = { code, msg ->
                historyManager.addHistory(name, msg)
                WorkResult.Failure(Exception(msg), msg)
            }
        )
    }

    private suspend fun processReward(): WorkResult {
        // 只有在周末才查询奖励（周六6点后到周一6点前）
        val calendar = Calendar.getInstance()
        val dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK)
        val hour = calendar.get(Calendar.HOUR_OF_DAY)
        
        val isWeekend = when (dayOfWeek) {
            Calendar.SATURDAY -> hour >= 6  // 周六6点以后
            Calendar.SUNDAY -> true          // 周日全天
            Calendar.MONDAY -> hour < 6      // 周一6点以前
            else -> false
        }
        
        if (!isWeekend) {
            // 非周末时间段，直接返回成功
            return WorkResult.Success
        }
        
        // 查询六门会武奖励
        val queryResult = gameApi.querySectMeleeReward()
        return queryResult.foldWithApiException(
            onSuccess = { response ->
                // 检查是否有可领取的奖励
                if (response.sectCheerReward.isNotEmpty() || response.sectWarfareReward.isNotEmpty()) {
                    // 有奖励可领取，执行领奖
                    val claimResult = gameApi.claimSectMeleeReward()
                    claimResult.foldWithApiException(
                        onSuccess = { claimResponse ->
                            historyManager.addHistory(name, claimResponse.getDescription())
                            WorkResult.Success
                        },
                        onFailure = { code, msg ->
                            if (code != -1011) { // 傻逼乐斗，pc版没有已领奖的字段，重复领奖不管
                                historyManager.addHistory(name, msg)
                                WorkResult.Failure(Exception(msg), msg)
                            } else {
                                WorkResult.Success
                            }
                        }
                    )
                } else {
                    WorkResult.Success
                }
            },
            onFailure = { code, msg ->
                historyManager.addHistory(name, msg)
                WorkResult.Failure(Exception(msg), msg)
            }
        )
    }
}